<?php
/**
 * Create by chang
 * Date 2019/12/20
 * Time 9:16
 *
 */

namespace app\common\service;

use app\admin\model\User;
use app\common\model\AgentShip;
use app\common\model\AgentShop;
use app\common\model\AgentStock;
use app\common\model\AgentStockRecord;
use app\common\model\ChainFunds;
use app\common\model\Commission;
use app\common\model\DestoryOrder;
use app\common\model\Order;
use app\common\model\OrderGoods;
use app\common\model\RewardRecord;
use think\Db;
use app\admin\model\User as UserModel;
use think\Exception;

class DestoryService extends Server
{
	
	/**
	 * 创建核销订单
	 * @param $id
	 * @param $userId
	 * @param $number
	 * @return array
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function createOrder($id, $userId, $number)
	{
		$row = Order::get(['id' => $id, 'user_id' => $userId, 'status' => Order::STATUS_SIGN]);
		if (!$row) {
			return $this->error('订单不存在');
		}
		
		$goods = OrderGoods::get(['order_id' => $id]);
		if ($row['order_type'] == Order::TYPE_GIFT && $number != $goods['last_number']) {
			return $this->error('赠送订单不能分批核销');
		}
		
		
		if ($goods['last_number'] < $number) {
			return $this->error('剩余数量为' . $goods['last_number']);
		}
		
		$model = new DestoryOrder();
		$res = $model->createOrder($id, $number);
		if ($res !== false) {
			return $this->success(['code' => $res]);
		}
		
		return $this->error('添加数据出错');
	}
	
	
	/**
	 * 根据核销码获取核销信息
	 * @param $code
	 * @return array
	 * @throws \think\exception\DbException
	 */
	public function getOrderByCode($code)
	{
		$row = DestoryOrder::get(['code' => $code, 'status' => DestoryOrder::STATUS_WAIT]);
		if (!$row) {
			return $this->error('核销订单不存在');
		}
		
		$order = Order::get(['id' => $row['order_id'], 'status' => Order::STATUS_SIGN]);
		if (!$order) {
			return $this->error('不是待核销订单');
		}
		
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => $order['id']])
			->find();
		if ($goods['last_number'] < $row['number']) {
			return $this->error('剩余数量小于核销数量');
		}
		$goods['goods_info'] = json_decode($goods['goods_info'], true);
		$goods['last_number'] = $row['number'];
		$order['goods'] = [$goods];
		
		return $this->success(['order' => $order, 'destoryOrder' => $row]);
	}
	
	
	/**
	 * 核销订单
	 * @param $order 订单信息
	 * @param $destoryOrder
	 * @param $agent 核销点信息
	 * @param $force 库存不足是否继续核销
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function destructOrder(
		$order,
		$destoryOrder,
		$agent,
		$force
	) {
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => $order['id']])
			->find();
		$goodsInfo = json_decode($goods['goods_info'], true);
		$goodsId = $goods['goods_id'];
		$specId = $goodsInfo['spec_id'];
		$number = $destoryOrder['number'];
		
		//减少库存
		$stockModel = new AgentStock();
		$stock = $stockModel->where([
			'user_id' => $agent['user_id'],
			'goods_id' => $goodsId,
			'spec_id' => $specId
		])->find();
		
		if (!$stock || $stock['number'] == 0) {
			return $this->error('你没有该商品的库存，不可核销!');
		}
		
		if ($stock['number'] < $number && $force == 0) {
			return $this->result('库存不足，当前库存' . $stock['number'] . ',是否继续核销部分商品？', -1, []);
		}
		
		$stockModel->startTrans();
		try {
			if ($stock['number'] >= $number && $goods['last_number'] == $number) {
				//更改订单状态
				$orderRes = Db::name('order')
					->where(['id' => $order['id']])
					->update([
						'status' => Order::STATUS_SUCCESS,
						'destruct_agent_id' => $agent['id'],
						'sign_time' => time(),
						'update_time' => time()
					]);
				
				if (!$orderRes) {
					throw new Exception('更改订单记录出错');
				}
			} else {
				//部分核销，更改核销码
				$orderRes = Db::name('order')
					->where(['id' => $order['id']])
					->update(['code' => $order['user_id'] . strrev(date('YmdHis')), 'update_time' => time()]);
			}
			if (!$orderRes) {
				throw new Exception('更改订单记录出错');
			}
			
			//实际核销数量
			$number = $stock['number'] >= $number ? $number : $stock['number'];
			
			//减少数量
			$goodsRes = Db::name('orderGoods')->where(['id' => $goods['id']])->setDec('last_number', $number);
			if (!$goodsRes) {
				throw new Exception('更改订单剩余数量出错');
			}
			
			$stockRes = $stockModel->add($agent['user_id'], $agent['id'], $goodsId, $specId, -$number);
			if (!$stockRes) {
				throw new Exception('减少库存出错');
			}
			
			//添加库存记录
			$recordModel = new AgentStockRecord();
			$recordRes = $recordModel->addRecord($agent['user_id'], $goodsId, $specId, $recordModel::TYPE_DESTRUCT,
				$number, '订单取货核销');
			if (!$recordRes) {
				throw new Exception('添加库存记录出错');
			}
			
			//添加核销记录
			$shipModle = new AgentShip();
			$shopRes = $shipModle->addRecore($order['id'], $agent['id'], $goodsId, $specId, $number, $order['code']);
			if (!$shopRes) {
				throw new Exception('添加核销记录出错');
			}
			
			$numberRes = Db::name('agentShop')
				->where(['id' => $agent['id']])
				->setInc('destory_number', $number);
			if (!$numberRes) {
				throw new Exception('添加核销数量出错');
			}
			
			//更改核销订单状态
			if (!empty($destoryOrder['id'])) {
				$destoryRes = Db::name('destoryOrder')
					->where(['id' => $destoryOrder['id']])
					->update([
						'status' => DestoryOrder::STATUS_SUCCESS,
						'number' => $number,
						'destory_time' => time(),
						'agent_id' => $agent['id']
					]);
				
				if (!$destoryRes) {
					throw new Exception('更新核销订单状态出错');
				}
			}
			
			
			if ($order['order_type'] != Order::TYPE_REWARD) {
				
				
				//获取设置信息(优先是单独设置的规则）
				$setting = Db::name('goodsRule')->where(['goods_id' => $goods['goods_id']])->find();
				//其它地区核销规则
				if ($order['area'] == UserModel::AREA_OTHER) {
					//发核销佣金, 核销点有5元，核销点上级提货点有5元，提货点的上级提货点算自己
					if (!$setting) {
						$setting = Db::name('setting')->find();
					}
					if ($setting && ($setting['shop_ship_amount'] > 0 || $setting['warehouse_amount'] > 0)) {
						$commissionModel = new Commission();
						//场景店,自己5元，归属提货点5元
						if ($agent['role'] == UserModel::LEVEL_SHOP) {
							
							if ($setting['shop_ship_amount'] > 0) {
								$shopRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'],
									$goodsId, $goods['id'], $setting['shop_ship_amount'] * $number, '场景店核销奖励',
									$commissionModel::TYPE_GOODS);
								
								if (!$shopRes) {
									throw new Exception('添加场景店核销奖励出错');
								}
							}
							
							if ($setting['warehouse_amount'] > 0 && $agent['warehouse_id']) {
								$warehouse = Db::name('agentShop')->find($agent['warehouse_id']);
								if ($warehouse && $warehouse['status'] == AgentShop::STATUS_Y) {
									$msg = '提货点下级核销奖励';
									$warehouseCommission = $setting['warehouse_amount'] * $number;
									$warehouseUserId = $warehouse['user_id'];
									//是连锁店，钱给上给
									if ($warehouse['chain_user_id']) {
										$warehouseUserId = $warehouse['chain_user_id'];
										$fundsRes = ChainFunds::addRecord($warehouseUserId, $warehouse['id'],
											$order['id'], $warehouseCommission, ChainFunds::TYPE_DESTORY);
										if (!$fundsRes) {
											throw new Exception('添加连锁佣金记录出错');
										}
										$msg = '连锁店下级提货点核销奖励';
									}
									
									$warehouseRes = $commissionModel->rebate($warehouseUserId, $order['user_id'],
										$order['id'], $goodsId, $goods['id'], $warehouseCommission, $msg,
										$commissionModel::TYPE_STOCK);
									if (!$warehouseRes) {
										throw new Exception('添加提货点奖励出错');
									}
								}
							}
						} else {
							if ($agent['role'] == UserModel::LEVEL_WAREHOUSE) {
								//销售是场景店，自己拿了核销和核销上级的钱
								$msg = '提货点核销奖励';
								$warehouse = $agent;
								//场景店
								if ($warehouse && $warehouse['role'] == UserModel::LEVEL_WAREHOUSE) {
									$warehouseCommission = ($setting['warehouse_amount'] + $setting['shop_ship_amount']) * $number;
									$warehouseUserId = $warehouse['user_id'];
									if ($warehouse['chain_user_id']) {
										$warehouseUserId = $warehouse['chain_user_id'];
										$fundsRes = ChainFunds::addRecord($warehouseUserId, $warehouse['id'],
											$order['id'], $warehouseCommission, ChainFunds::TYPE_DESTORY);
										if (!$fundsRes) {
											throw new Exception('添加连锁佣金记录出错');
										}
										$msg = '连锁店下级提货点核销奖励';
									}
									
									$warehouseRes = $commissionModel->rebate($warehouseUserId, $order['user_id'],
										$order['id'], $goodsId, $goods['id'], $warehouseCommission, $msg,
										$commissionModel::TYPE_GOODS);
									if (!$warehouseRes) {
										throw new Exception('添加提货点奖励出错');
									}
									
								}
							}
						}
						
						
					}
				} else {
					$globalSetting = Db::name('ruleSz')->find();
					//核销佣金
					$destoryCommission = $setting ? $setting['sz_destory_amount'] : $globalSetting['destory_amount'];
					//火爆街铺货佣金
					$centerStockCommission = $setting ? $setting['sz_parent_amount'] : $globalSetting['parent_amount'];
					
					//提货点铺货佣金
					$warehouseStockCommission = 0;
					
					//查找是否提货点核销自己的推广订单
					if ($order['recommend_user_id'] == $agent['user_id'] && $agent['role'] == UserModel::LEVEL_WAREHOUSE) {
						$warehouseStockCommission = $setting ? $setting['warehouse_sale'] : $globalSetting['warehouse_sale'];
						$centerStockCommission = $setting ? $setting['warehouse_parent'] : $globalSetting['warehouse_parent'];
					}
					
					$centerAgentId = $agent['role'] == UserModel::LEVEL_CENTER ? $agent['id'] : $agent['center_id'];
					
					// 代言人赠送订单，提货点核销每瓶5元,发展中心核销每瓶10元
					if ($order['order_type'] == Order::TYPE_GIFT) {
						$destoryCommission = 5;
						// 发展中心核销不是自己的订单，每瓶10元
						$recommendUser = User::get($order['recommend_user_id']);
						if ($agent['role'] == UserModel::LEVEL_CENTER && $agent['user_id'] != $order['recommend_user_id'] && $recommendUser['level'] == UserModel::LEVEL_WAREHOUSE) {
							$destoryCommission = 10;
						}
					}
					$commissionModel = new Commission();
					//添加核销佣金
					if ($destoryCommission > 0) {
						$destoryCommission = $destoryCommission * $number;
						$destoryRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'],
							$goodsId, $goods['id'], $destoryCommission, '核销奖励(深圳)', $commissionModel::TYPE_GOODS);
						if (!$destoryRes) {
							throw new Exception('添加核销奖励出错');
						}
					}
					
					if ($order['order_type'] != Order::TYPE_GIFT) {
						//添加火爆街
						if ($centerStockCommission > 0 && $centerAgentId) {
							$centerAgent = AgentShop::get(['id' => $centerAgentId, 'status' => AgentShop::STATUS_Y]);
							if ($centerAgent) {
								$centerStockCommission = $centerStockCommission * $number;
								$centerRes = $commissionModel->rebate($centerAgent['user_id'], $order['user_id'],
									$order['id'], $goodsId, $goods['id'], $centerStockCommission, '火爆街铺货佣金(深圳)',
									$commissionModel::TYPE_STOCK);
								if (!$centerRes) {
									throw new Exception('添加火爆街铺货佣金出错');
								}
							}
						}
						
						//场景店核销别人的有2元铺货佣金
						if ($warehouseStockCommission > 0) {
							$warehouseStockCommission = $warehouseStockCommission * $number;
							$warehouseRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'],
								$goodsId, $goods['id'], $warehouseStockCommission, '提货点铺货佣金(深圳)',
								$commissionModel::TYPE_STOCK);
							if (!$warehouseRes) {
								throw new Exception('添加提货点铺货佣金出错');
							}
						}
					}
				}
			} else {
				//添加代理的待核销赠酒数量
				$addRes = Db::name('agentShop')
					->where(['id' => $agent['id']])
					->setInc('gift_number', $number);
				if(!$addRes) {
					throw new Exception('添加代理赠酒数量出错');
				}
				
				$recordRes = RewardRecord::addRecord($agent['user_id'], $number, '核销订单ID【'.$order['id'].'】赠酒数量');
				if(!$recordRes) {
					throw new Exception('添加赠酒记录出错');
				}
			}
			
			$goods = Db::name('orderGoods')->where(['id' => $goods['id']])->find();
			
			//查找是否有返利
			$rebateRow = Db::name('commission')
				->where(['order_id' => $order['id'], 'status' => Commission::STATUS_WAIT])
				->find();
			
			//订单状态为待结算且全部商品已核销完后更改佣金状态为已结算
			if ($rebateRow && $goods['last_number'] == 0) {
				$commissionModel = new Commission();
				$commissionRes = $commissionModel->send($order['id']);
				if (!$commissionRes) {
					throw new Exception($commissionModel->getError());
				}
			}
			
			$service = new OrderService();
			$parentDestoryRes = $service->addParentDestoryNumber($agent, $number, $order['id'], $goodsId, $specId,
				$order['code']);
			if (!$parentDestoryRes) {
				throw new Exception($service->getError());
			}
			$stockModel->commit();
			
			return $this->success();
		} catch (Exception $e) {
			$stockModel->rollback();
			return $this->error($e->getMessage());
		}
	}
	
	/**
	 * 根据用户ID获取未核销商品及当前扫码的代理对应库存
	 * @param $userId
	 * @param $agentUserId
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getUserDestoryGoodsAndAgentStore($userId, $agentUserId)
	{
		$agent = AgentShop::getInfoByUserId($agentUserId);
		if (!$agent || $agent['status'] != AgentShop::STATUS_Y) {
			$this->errorMsg = '代理不存在或已禁用';
			return false;
		}
		
		$orders = Db::name('order')
			->where(['user_id' => $userId, 'status' => Order::STATUS_SIGN])
			->column('id', 'order_no');
		if (!$orders) {
			$this->errorMsg = '没有待核销订单';
			return false;
		}
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => ['in', $orders]])
			->field('id, goods_id, goods_info, last_number')
			->select();
		if (!$goods) {
			$this->errorMsg = '没有待核销商品';
			return false;
		}
		
		$list = [];
		foreach ($goods as $item) {
			$goodsInfo = json_decode($item['goods_info'], true);
			$goodsId = $item['goods_id'];
			$specId = $goodsInfo['spec_id'];
			$key = $goodsId . '_' . $specId;
			if (!isset($list[$key])) {
				$list[$key] = [
					'goods_id' => $goodsId,
					'spec_id' => $specId,
					'number' => 0,
					'goods_name' => $goodsInfo['name'],
					'spec_name' => $goodsInfo['spec_name'],
					'image' => $goodsInfo['spec_image'] ?: $goodsInfo['image'],
					'agent_stock' => 0
				];
				
				$store = Db::name('agentStock')
					->where([
						'agent_shop_id' => $agent['id'],
						'goods_id' => $goodsId,
						'spec_id' => $specId
					])->find();
				if ($store) {
					$list[$key]['agent_stock'] = $store['number'];
				}
			}
			
			$list[$key]['number'] += $item['last_number'];
		}
		
		return array_values($list);
	}
	
	public function userDestoryGoods($userId, $agentUserId, $goods)
	{
		$agent = AgentShop::getInfoByUserId($agentUserId);
		if (!$agent || $agent['status'] != AgentShop::STATUS_Y) {
			$this->errorMsg = '代理不存在或已禁用';
			return false;
		}
		if (!$goods) {
			$this->errorMsg = '参数错误';
			return false;
		}
		
		$goodsIds = [];
		$destoryList = [];
		foreach ($goods as $item) {
			if ($item['number'] > 0) {
				$goodsIds[] = $item['goods_id'];
				$destoryList[$item['goods_id'] . '_' . $item['spec_id']] = $item;
			}
		}
		
		if (!$goodsIds) {
			$this->errorMsg = '核销数量不能为空';
			return false;
		}
		
		$orderGoods = Db::name('orderGoods')->alias('og')
			->join('order o', 'og.order_id = o.id', 'left')
			->where([
				'o.user_id' => $userId,
				'og.goods_id' => ['in', $goodsIds],
				'o.status' => Order::STATUS_SIGN
			])
			->field('og.id, og.order_id, og.goods_id, og.last_number, og.goods_info')
			->select();
		
		if (!$orderGoods) {
			$this->errorMsg = '要核销的商品订单不存在';
			return false;
		}
		
		
		foreach ($orderGoods as $item) {
			$goodsInfo = json_decode($item['goods_info'], true);
			$specId = $goodsInfo['spec_id'];
			$key = $item['goods_id'] . '_' . $specId;
			if (!isset($destoryList[$key]) || $destoryList[$key]['number'] < 1) {
				continue;
			}
			
			$order = Order::get($item['order_id']);
			$destoryRes = $this->destructOrder($order, ['number' => $destoryList[$key]['number']], $agent, true);
			if (!$destoryRes['status']) {
				$this->errorMsg = $destoryRes['msg'];
				return false;
			}
		}
		
		
		return [
			'date' => date('Y-m-d H:i:s'),
			'agent_name' => $agent['name']
		];
	}
}
